

import java.io.IOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessionbeans.LoginBeanRemote;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public LoginServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username,password,loginResult;
		
		username = request.getParameter("username");
		password = request.getParameter("password");
		if (username != null && password != null) {
			try {
				InitialContext context = new InitialContext();
				Object ref = context.lookup("LoginBeanRemote");
	    		LoginBeanRemote loginBean = (LoginBeanRemote)PortableRemoteObject.narrow(ref, LoginBeanRemote.class);
				loginResult = loginBean.verifyCredentials(username,password);
				if (loginResult.equals("registered")) {
					request.getSession().setAttribute("userId",username);
					request.getSession().setAttribute("redirected", "SearchPage.jsp");
				//	request.getSession().setMaxInactiveInterval(0);
					response.sendRedirect("GetAbilitiesServlet");
				}
				else if (loginResult.equals("admin")) {
					request.getSession().setAttribute("userId",username);
			//		request.getSession().setMaxInactiveInterval(0);
					response.sendRedirect("AdminPage.jsp");
				}
				else {
					request.getSession().setAttribute("redirected","Index.jsp");
					request.getSession().setAttribute("message","Unknown user!");
					response.sendRedirect("Message.jsp");
				}
			} catch (NamingException e) {
				response.getWriter().println("Naming Exception");
				e.printStackTrace();
			}
		}
		else {
			request.getSession().setAttribute("redirected","Index.jsp");
			request.getSession().setAttribute("message","Error during login");
			response.sendRedirect("Message.jsp");
		}
	}
}
